package it.softphone.commons.util.web;


import static it.softphone.commons.util.LogUtil.logger;

import it.softphone.commons.util.PasswordManager;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


/**
 * 
 * @author softphone
 *
 */
public class EncodePasswordListener implements ServletContextListener {
	private static final String CONFIG_FILE = "configFile";

	/**
	 * <pre>
	 * 
	 * encode password in property file 
	 * 
	 * The property file name is retrieved from 'configFile' context property
	 * 
	 * </pre>
	 * 
	 * @param context
	 */
	public static void exec( ServletContext context ) {
		if( context == null ) throw new IllegalArgumentException("context param is null!");
		
		String configFile = context.getInitParameter(CONFIG_FILE);
		
		if( null==configFile ) {
			final String msg = String.format( "init parameterer [%s] undefined!", CONFIG_FILE);
			logger.error( msg );
			return;
		}
		
		String path = context.getRealPath(configFile);
		if( null==path ) {
			final String msg = String.format( "path [%s] not found!", path);			
			logger.error( msg );
			return;
		}
		
		
		try {
			java.io.File propertiesFile = new java.io.File( path );
			
			PasswordManager.encodePropertiesFile(propertiesFile);
			
		} catch (IOException e1) {
			final String msg = String.format( "error loading config file [%s] undefined!", CONFIG_FILE);
			logger.error( msg, e1 );
			return;
		}
		
		
		
	}
	public void contextInitialized(ServletContextEvent sce) {
		
		exec( sce.getServletContext() );		
	}
	
	public void contextDestroyed(ServletContextEvent sce) {

	}


}
